/*
	Created By thinkmix 2017-02-07,
	JavascriptBridge With Native
	require base64.js
 */

! function (a, b) {
    "function" == typeof define && (define.amd || define.cmd) ? define(function () {
        return b(a)
    }) : b(a);
}(window, function (a) {
    var URL = getLocalPath(),
        OS_TYPE = getUserAgent(),
        DEV = process.env.NODE_ENV === 'development'; // 是否是开发模式

    function getLocalPath () {
        var _url = window.location.href;
        _url = _url.split('.html')[0].split('/');
        _url.splice(_url.length - 1, 1);
        return _url.join('/') + '/';
    }
    // 判断终端类型
    function getUserAgent () {
        let ua = navigator.userAgent.toLowerCase();

        var t = (navigator.appVersion, ua.indexOf("android") > -1 || ua.indexOf("linux") > -1),
            n = !!ua.match(/\(i[^;]+;( U;)? cpu.+mac os x/);
        return t ? 2 : n ? 1 : void 0 // 1:ios,2:andriod
    }
    // 设置url
    function setSourceUrl (url) {
        if (url.indexOf("http") === -1) {
            return URL + url.replace(/.html/g, '.' + APP_SOURCE.appId + '.html');
        } else {
            return url;
        }
    }
    // 连接测试
    function connect (init, callback) {
        if (2 == OS_TYPE && window.WebViewJavascriptBridge ? init(WebViewJavascriptBridge) : document.addEventListener('WebViewJavascriptBridgeReady', function () {
            init(WebViewJavascriptBridge)
            callback();
        }, !0), 1 == OS_TYPE) {
            window.WVJBCallbacks = [init];
            var WVJBIframe = document.createElement('iframe');
            WVJBIframe.style.display = 'none';
            WVJBIframe.src = 'https://__bridge_loaded__';
            document.documentElement.appendChild(WVJBIframe);
            setTimeout(function () { document.documentElement.removeChild(WVJBIframe) }, 0);
            callback();
        }
    }
    // call app function
    function callHandler (props) {
        let data = props.data ? BASE64.encode(JSON.stringify(props.data)) : '';

        if (window.WebViewJavascriptBridge) {
            window.WebViewJavascriptBridge.callHandler(
                props.name,
                data,
                function (result) {
                    // 这个接口返回的是string
                    if (props.name === 'isConnected') {
                        props.callback(result);
                    } else if (result) {
                        try {
                            result = JSON.parse(BASE64.decode(result));
                            typeof props.callback === 'function' && props.callback(result);
                        } catch (error) {
                            alert('交互数据解析错误');
                        }
                    }
                }
            )
        }
    }
    a.Jsborya = {
        ready: function (callback) {
            connect(function (bridge) {
                bridge.init(function (message, responseCallback) {
                    console.log('connect success ！', message);
                });
            }, callback);
        },
        webviewLoading: function (json) { // app加载层控制
            callHandler({
                name: 'webViewLoading',
                data: json,
                callback: function (result) {
                    console.log('webviewLoading');
                }
            });
        },
        pageJump: function (json) { // 页面跳转
            json.url = setSourceUrl(json.url);
            if (!json.hasOwnProperty('destroyed')) json.destroyed = false; // 默认是不销毁当前视图

            if (DEV) {
                window.location.href = json.url;
            }

            callHandler({
                name: 'pageJump',
                data: json,
                callback: function (result) {
                    try {
                        if (typeof json.complete == 'function') json.complete(result);
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        pageBack: function (json) { // 页面返回
            json.url = setSourceUrl(json.url);
            if (!json.hasOwnProperty('isLoad')) json.isLoad = false; // 默认不刷新上一视图

            if (DEV) {
                window.location.href = json.url;
            }

            callHandler({
                name: 'pageBack',
                data: json,
                callback: function (result) {
                    console.log('pageBack');
                }
            });
        },
        pageReload: function (json) { // 页面重载
            json.url = setSourceUrl(json.url);

            if (DEV) {
                window.location.href = json.url;
            }

            callHandler({
                name: 'pageReload',
                data: json,
                callback: function (result) {
                    console.log('pageReload');
                }
            });
        },
        getUserInfo: function (callback) { // 获取app用户信息
            if (DEV) {
                callback({
                    "applicationID": "CM-1591253587816-1278283032",
                    "timestamp": "1591254073487",
                    "token": "9hKloCBQrdbMNxrcptJnHX/tlOc6VIvH55+nsqfwZWPm+Py4rSgHiYf1AM77IS1x4fkrOl6ZaNLhaalB6uLpBTA/Bu5GAgx8K0QnJTRmXujE3CVYq50oGSHwEiflAZCXDrhfGgDIzsn/i9LI3zN4ZODSlujXsNFuoWFWtqh10k7GHgozdolT4V4RxTuHWasF",
                    "userId": "200414805525"
                });
            }

            callHandler({
                name: 'getUserInfo',
                data: '',
                callback: function (result) {
                    try {
                        result.applicationID = result.applicationId;
                        result.userId = result.uid;

                        delete result.uid;
                        delete result.applicationId;

                        callback(result);
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        updateVersion: function (json) { // app弹出版本更新
            callHandler({
                name: 'updateVersion',
                data: json,
                callback: function (result) {
                    console.log('updateVersion');
                }
            });
        },
        isConnected: function (callback) { // 判断app是否连接蓝牙设备
            callHandler({
                name: 'isConnected',
                data: '',
                callback: function (result) {
                    callback(result);
                }
            });
        },
        dialog: function (json) { // app弹出框
            callHandler({
                name: 'dialog',
                data: json,
                callback: function (result) {
                    json.yes ? json.yes(result) : console.log('dialog');
                }
            });
        },
        callPay: function (json) { // 支付
            callHandler({
                name: 'callPay',
                data: json,
                callback: function (result) {
                    try {
                        json.complete(result);
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        httpRequest: function (json) { // 通过app代理请求
            callHandler({
                name: 'httpRequest',
                data: json,
                callback: function (result) {
                    try {
                        json.complete(result);
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
        setHeader: function (json) { // 设置app标题
            callHandler({
                name: 'setHeader',
                data: json,
                callback: function (result) {
                    console.log('setHeader');
                }
            });
        },
        registerHandler: function (json) { // 注册桥接函数
            window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.registerHandler(json.name, function (result) {
                try {
                    json.action(result ? JSON.parse(BASE64.decode(result)) : '');
                } catch (e) {
                    console.log(e);
                }
            });
        },
        getAuth: function (json) {
            if (DEV) {
                json.complete({
                    boryaAuth: "200414805525,2020052100,10,2,1,9399177956326070"
                })
            }

            callHandler({
                name: 'getAuth',
                data: json.data,
                callback: function (result) {
                    try {
                        json.complete(result);
                    } catch (e) {
                        console.log(e);
                    }
                }
            });
        },
    }
});